package com.cms.admin.action;


import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cms.admin.core.http.HttpClientHelper;
import com.cms.admin.core.util.RequestUtil;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse.Credentials;
import com.cms.admin.util.Constants;
import com.cms.admin.util.DateUtils;
import com.cms.admin.util.FtpClient;
import com.cms.admin.util.PropertiesService;
import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements SessionAware,
        ServletRequestAware, ServletResponseAware {
    private static Log log = LogFactory.getLog(BaseAction.class);
    public static final String VIEW = "view";
    public static final String LIST = "list";
    public static final String STATUS = "status";
    public static final String WARN = "warn";
    public static final String SUCCESS = "success";
    public static final String ERROR = "error";
    public static final String MESSAGE = "message";
    public static final String CONTENT = "content";

    protected static HttpServletRequest request = null;
    protected static HttpServletResponse response = null;
    protected static Map att = null;
    public static int BUFFER_SIZE = 2048;
    private static String path = null;
    private static String basePath = null;
    private static boolean isWindwos = true;
    public static String contextPath = null;
    public static Map pathMap = null;
    public static Map osInfo = null;

    public String ajax(String content, String type) {
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            // HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType(type + ";charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(content);
            response.getWriter().flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AJAX????????????null
     *
     * @param - ???????
     * @return String - String
     */
    public String ajaxText(String text) {
        return ajax(text, "text/plain");
    }

    /**
     * AJAX???HTML??????null
     *
     * @param html - html????
     * @return String - String
     */
    public String ajaxHtml(String html) {
        return ajax(html, "text/html");
    }

    /**
     * AJAX???XML??????null
     *
     * @param xml - xml
     * @return String - String
     */
    public String ajaxXml(String xml) {
        return ajax(xml, "text/xml");
    }

    /**
     * ????Map???JSON??????null
     *
     * @param jsonMap - map
     * @return String - json??????????
     */
    public String ajaxJson(Map jsonMap) {
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "text/html");
    }

    public String ajaxJson(JSONObject jsonObject) {
        return ajax(jsonObject.toString(), "text/html");
    }

    /**
     * ????????????JSON??????null
     *
     * @param jsonString - ?????????
     * @return String - ????????String
     */
    public String ajaxJson(String jsonString) {
        return ajax(jsonString, "text/html");
    }

    /**
     * ???JSON?????????????null
     *
     * @param message - ???????
     * @return String - json?????????????
     */
    public String ajaxJsonWarnMessage(String message) {
        Map jsonMap = new HashMap();
        jsonMap.put(STATUS, WARN);
        jsonMap.put(MESSAGE, message);
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "text/html");
    }

    /**
     * ???JSON????????????null
     *
     * @param message - ???????
     * @return String - json??????????
     */
    public String ajaxJsonSuccessMessage(String message) {
        Map jsonMap = new HashMap();
        jsonMap.put(STATUS, SUCCESS);
        jsonMap.put(MESSAGE, message);
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "text/html");
    }

    /**
     * ???JSON????????????null
     *
     * @param obj - ???????
     * @return String - json??????????
     */
    public String ajaxJsonSuccessMessage(JSONObject obj) {
        obj.put(STATUS, SUCCESS);
        return ajax(obj.toString(), "text/html");
    }

    /**
     * ???JSON?????????????null
     *
     * @param message - ???????????
     * @return String - json???????????
     */
    public String ajaxJsonErrorMessage(String message) {
        Map jsonMap = new HashMap();
        jsonMap.put(STATUS, ERROR);
        jsonMap.put(MESSAGE, message);
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "text/html");
    }

    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;

    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;

    }

    @Override
    public void setSession(Map<String, Object> att) {
        this.att = att;

    }

    public void initBathPath() {
        if (null == basePath) {
            if (null != request) {
                basePath = request.getScheme() + "://" + request.getServerName()
                        + ":" + request.getServerPort() + request.getContextPath();
            }
        }
    }

    /**
     * @return the basePath
     */
    public String getBasePath() {
        return basePath;
    }


    /**
     * @param basePath the basePath to set
     */
    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }


    public static String getRootPath() throws Exception {
        if (null != request) {
            path = request.getContextPath();
            basePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + path;

            ServletContext servletContext = request.getSession().getServletContext();
            contextPath = servletContext.getRealPath("");

            pathMap = (Map) servletContext.getAttribute("pathMap");
            osInfo = (Map) servletContext.getAttribute("OSMap");
        }
        //	System.out.println("contextPath:" + contextPath);
        //	System.out.println("basePath:" + basePath);
        //	System.out.println("pathMap:" + pathMap);
        // 	System.out.println("osInfo:" + osInfo);

        return contextPath;
    }

    public String uploadSinglePicProcess(File srcFile, String srcFileName, String srcFileContentTypeName) throws Exception {
        // ??????????????????
        getRootPath();

        // ?????????????

        //??????????????·??
        String srcFilePath = "";

        //δ??????????????·??
        String destPath = "";

        //????????????????·??
        String destFilePath = "";


        //???
        String tailSuffix = getExtension(srcFileName);


        // ?????????????????????????
        String savePath = contextPath;


        String serverPathPrefix = null;

        log.info("contextPath:" + contextPath);
        if (osInfo.get("os.name").toString().contains("Windows")) {


            savePath = contextPath + File.separator + pathMap.get("windows.upload.model.gallery.path");
            serverPathPrefix = (String) pathMap.get("windows.upload.model.gallery.path");


        } else if (osInfo.get("os.name").toString().contains("Linux") || osInfo.get("os.name").toString().contains("linux") || osInfo.get("os.name").toString().contains("Unix") || osInfo.get("os.name").toString().contains("unix")) {


            savePath = contextPath + File.separator + pathMap.get("unix.upload.model.gallery.path");

            serverPathPrefix = (String) pathMap.get("unix.upload.model.gallery.path");
        }

        destPath = savePath + File.separator;


        String uniqueName = uniqueName(destPath);

        String DIR = serverPathPrefix + File.separator;

        String URI = serverPathPrefix + File.separator + srcFileName;

        log.info("URI:" + URI);
        destFilePath = destPath + srcFileName;
        log.info("destFilePath:" + destFilePath);


        if (null != srcFile) {
            srcFilePath = srcFile.getAbsolutePath();
        } else {
            log.info(srcFileName + "File is null:");
            log.info(srcFileName + "File is null:");
            log.info(srcFileName + "File is null:");
            //??????????????????洢?????????????·??
            return "";
        }

        if (!fileExists(destPath)) {


            makeDir(destPath);

        }

        File src = new File(srcFilePath);
        File dest = new File(destFilePath);
        copy(src, dest, DIR);

        return URI;


    }


    public String uploadSinglePicProcess4OneArmBanditCfg(File srcFile, String srcFileName, String srcFileContentTypeName) throws Exception {

        getRootPath();
        String srcFilePath = "";
        String destPath = "";
        String destFilePath = "";
        String tailSuffix = getExtension(srcFileName);
        String savePath = contextPath;


        String serverPathPrefix = null;

        log.info("contextPath:" + contextPath);
        if (osInfo.get("os.name").toString().contains("Windows")) {
            savePath = contextPath + File.separator + pathMap.get("windows.upload.AD.gallery.path");
            serverPathPrefix = (String) pathMap.get("windows.upload.AD.gallery.path");
        } else if (osInfo.get("os.name").toString().contains("Linux") || osInfo.get("os.name").toString().contains("linux") || osInfo.get("os.name").toString().contains("Unix") || osInfo.get("os.name").toString().contains("unix")) {
            savePath = contextPath + File.separator + pathMap.get("unix.upload.AD.gallery.path");
            serverPathPrefix = (String) pathMap.get("unix.upload.AD.gallery.path");
        }

        destPath = savePath + File.separator + DateUtils.todayDate() + File.separator;
        String uniqueName = uniqueName(destPath);

        String DIR = serverPathPrefix + "/" + DateUtils.todayDate() + "/";
        String URI = DIR + uniqueName + tailSuffix;

        destFilePath = destPath + uniqueName + tailSuffix;

        if (null != srcFile) {
            srcFilePath = srcFile.getAbsolutePath();
        } else {
            return "";
        }

        if (!fileExists(destPath)) {
            makeDir(destPath);

        }

        File src = new File(srcFilePath);
        File dest = new File(destFilePath);

        copy(src, dest, DIR);

        return URI;

    }

    public String uploadSinglePicProcess4Ad(File srcFile, String srcFileName, String srcFileContentTypeName) throws Exception {
        getRootPath();
        String srcFilePath = "";
        String destPath = "";
        String destFilePath = "";
        String tailSuffix = getExtension(srcFileName);
        String savePath = contextPath;
        String serverPathPrefix = null;

        log.info("contextPath:" + contextPath);
        if (osInfo.get("os.name").toString().contains("Windows")) {
            savePath = contextPath + File.separator + pathMap.get("windows.upload.AD.gallery.path");
            serverPathPrefix = (String) pathMap.get("windows.upload.AD.gallery.path");


        } else if (osInfo.get("os.name").toString().contains("Linux") || osInfo.get("os.name").toString().contains("linux") || osInfo.get("os.name").toString().contains("Unix") || osInfo.get("os.name").toString().contains("unix")) {
            savePath = contextPath + File.separator + pathMap.get("unix.upload.AD.gallery.path");
            serverPathPrefix = (String) pathMap.get("unix.upload.AD.gallery.path");
        }


        destPath = savePath + File.separator + DateUtils.todayDate() + File.separator;
        String uniqueName = uniqueName(destPath);
        String DIR = serverPathPrefix + "/" + DateUtils.todayDate() + "/";
        String URI = DIR + uniqueName + tailSuffix;
        destFilePath = destPath + uniqueName + tailSuffix;
        if (null != srcFile) {
            srcFilePath = srcFile.getAbsolutePath();
        } else {
            return "";
        }

        if (!fileExists(destPath)) {


            makeDir(destPath);

        }

        File src = new File(srcFilePath);

        File dest = new File(destFilePath);
        copy(src, dest, DIR);

        return URI;


    }

    public String uploadSinglePicProcess4FisrtPage(File srcFile, String srcFileName, String srcFileContentTypeName) throws Exception {

        getRootPath();

        String srcFilePath = "";

        String destPath = "";

        String destFilePath = "";

        String tailSuffix = getExtension(srcFileName);

        String savePath = contextPath;

        String serverPathPrefix = null;

        log.info("config path:" + osInfo.get("os.name"));
        if (osInfo.get("os.name").toString().contains("Windows")) {


            savePath = contextPath + File.separator + pathMap.get("windows.upload.FisrtPage.gallery.path");
            serverPathPrefix = (String) pathMap.get("windows.upload.FisrtPage.gallery.path");


        } else if (osInfo.get("os.name").toString().contains("Linux") || osInfo.get("os.name").toString().contains("linux") || osInfo.get("os.name").toString().contains("Unix") || osInfo.get("os.name").toString().contains("unix")) {

            savePath = contextPath + File.separator + pathMap.get("unix.upload.FisrtPage.gallery.path");

            serverPathPrefix = (String) pathMap.get("unix.upload.FisrtPage.gallery.path");
        }

        destPath = savePath + File.separator;

        String uniqueName = srcFileName;

        String DIR = serverPathPrefix + "/";
        String URI = DIR + uniqueName;
        log.info("URI:" + URI);
        destFilePath = savePath + File.separator + uniqueName;


        destFilePath = destPath + uniqueName;
        log.info("destFilePath:" + destFilePath);

        if (null != srcFile) {
            srcFilePath = srcFile.getAbsolutePath();
        } else {
            //??????????????????洢?????????????·??
            return "";
        }


        File src = new File(srcFilePath);

        File dest = new File(destFilePath);


        // ??????????????????
        if (!fileExists(destPath)) {


            makeDir(destPath);

        }

        // ??????????????????????
        copy(src, dest, DIR);

        // ??????????,??????·?????浽???????


        return URI;


    }


    public String uploadSinglePicValuableScenic(File srcFile, String srcFileName, String srcFileContentTypeName) throws Exception {
        // ??????????????????
        getRootPath();

        // ?????????????

        //??????????????·??
        String srcFilePath = "";

        //δ??????????????·??
        String destPath = "";

        //????????????????·??
        String destFilePath = "";
        //???
        String tailSuffix = getExtension(srcFileName);


        // ?????????????????????????
        String savePath = contextPath;

        String serverPathPrefix = null;

        log.info("config path:" + osInfo.get("os.name"));
        if (osInfo.get("os.name").toString().contains("Windows")) {


            savePath = contextPath + File.separator + pathMap.get("windows.upload.ValuableScenic.gallery.path");
            serverPathPrefix = (String) pathMap.get("windows.upload.ValuableScenic.gallery.path");


        } else if (osInfo.get("os.name").toString().contains("Linux") || osInfo.get("os.name").toString().contains("linux") || osInfo.get("os.name").toString().contains("Unix") || osInfo.get("os.name").toString().contains("unix")) {


            savePath = contextPath + File.separator + pathMap.get("unix.upload.ValuableScenic.gallery.path");

            serverPathPrefix = (String) pathMap.get("unix.upload.ValuableScenic.gallery.path");
        }

        //??洢??????
        destPath = savePath + File.separator;

        //????????????????
        String uniqueName = srcFileName;

        //???URI
        String DIR = serverPathPrefix + "/";
        String URI = DIR + uniqueName;
        log.info("URI:" + URI);
        destFilePath = savePath + File.separator + uniqueName;


        destFilePath = destPath + uniqueName;
        log.info("destFilePath:" + destFilePath);


        //?????????
        if (null != srcFile) {
            srcFilePath = srcFile.getAbsolutePath();
        } else {
            //??????????????????洢?????????????·??
            return "";
        }

        File src = new File(srcFilePath);

        File dest = new File(destFilePath);

        // ??????????????????
        if (!fileExists(destPath)) {
            makeDir(destPath);
        }
        // ??????????????????????
        copy(src, dest, DIR);

        // ??????????,??????·?????浽???????
        return URI;
    }


    public String uploadSinglePicTaskMode(File srcFile, String srcFileName, String srcFileContentTypeName) throws Exception {
        getRootPath();
        String srcFilePath = "";
        String destPath = "";
        String destFilePath = "";
        String tailSuffix = getExtension(srcFileName);
        String savePath = contextPath;

        String serverPathPrefix = null;

        log.info("config path:" + osInfo.get("os.name"));
        if (osInfo.get("os.name").toString().contains("Windows")) {


            savePath = contextPath + File.separator + pathMap.get("windows.upload.taskMode.gallery.path");
            serverPathPrefix = (String) pathMap.get("windows.upload.taskMode.gallery.path");


        } else if (osInfo.get("os.name").toString().contains("Linux") || osInfo.get("os.name").toString().contains("linux") || osInfo.get("os.name").toString().contains("Unix") || osInfo.get("os.name").toString().contains("unix")) {


            savePath = contextPath + File.separator + pathMap.get("unix.upload.taskMode.gallery.path");

            serverPathPrefix = (String) pathMap.get("unix.upload.taskMode.gallery.path");
        }

        //??洢??????
        destPath = savePath + File.separator;

        //????????????????
        String uniqueName = srcFileName;

        //???URI
        String DIR = serverPathPrefix + "/";
        String URI = DIR + uniqueName;
        log.info("URI:" + URI);
        destFilePath = savePath + File.separator + uniqueName;


        destFilePath = destPath + uniqueName;
        log.info("destFilePath:" + destFilePath);

        if (null != srcFile) {
            srcFilePath = srcFile.getAbsolutePath();
        } else {

            return "";
        }

        File src = new File(srcFilePath);

        File dest = new File(destFilePath);

        if (!fileExists(destPath)) {
            makeDir(destPath);
        }

        copy(src, dest, DIR);

        return URI;
    }


    public void deleteFileByPathProcess(String originalPath, String newPath) throws Exception {
        deleteFromFtp(originalPath);
        deleteFromFtp(newPath);

        String root = getRootPath();

        originalPath = root + originalPath;
        newPath = root + "/" + newPath;
        System.out.println("originalPath:" + originalPath);
        System.out.println("newPath:" + newPath);
        File f = null;


        if (fileExists(originalPath)) {

            f = new File(originalPath);
            if (null != f) {
                f.delete();
            }

        }

        if (fileExists(newPath)) {

            f = new File(newPath);
            if (null != f) {
                f.delete();
            }

        }


    }


    /**
     * ??????????????
     *
     * @param realPath
     * @throws Exception
     */
    public static void deleteFromFtp(String realPath) throws Exception {

        if (StringUtils.isNotBlank(realPath)) {

            FtpClient client = new FtpClient(
                    PropertiesService.getString("ftp.upload.ip"),
                    Integer.valueOf("21"),
                    PropertiesService.getString("ftp.upload.username"),
                    PropertiesService.getString("ftp.upload.password"));
            try {
                String ftpPath = PropertiesService.getString("ftp.upload.path");
                String fileName = "";
                if (client.connect()) {

                    if (realPath.indexOf("/") > 0) {
                        ftpPath = ftpPath + "/" + realPath.substring(0, realPath.lastIndexOf("/"));
                        fileName = realPath.substring(realPath.lastIndexOf("/") + 1, realPath.length());
                    } else {

                        fileName = realPath;
                    }
                    client.deleteFile("", ftpPath, fileName);

                }

            } catch (Exception e) {

            } finally {
                client.disconnect();
            }
        }

    }

    public static String getExtension(String fileName) throws Exception {

        if (null != fileName) {
            int pos = fileName.lastIndexOf(".");
            if (pos > 0) {
                return fileName.substring(pos);
            }

        }
        return "";

    }


    public static String getFileNameNoEx(String filename) {

        if ((filename != null) && (filename.length() > 0)) {

            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    public static String uniqueName(String dir) throws Exception {
        String filename = "";
        while (null == filename || "".equals(filename)) {
            filename = randomFilename();
            if (fileExists(dir + filename + ".jpg")
                    || fileExists(dir + filename + ".gif")
                    || fileExists(dir + filename + ".doc")
                    || fileExists(dir + filename + ".txt")
                    || fileExists(dir + filename + ".docx")
                    || fileExists(dir + filename + ".xls")
                    || fileExists(dir + filename + ".ppt")
                    || fileExists(dir + filename + ".zip")
                    || fileExists(dir + filename + ".png")
                    || fileExists(dir + filename + ".apk")
                    || fileExists(dir + filename + ".APK")) {
                filename = "";
            }
        }

        return filename;
    }

    public static boolean fileExists(String fileName) throws Exception {


        if (null != fileName && !"".equals(fileName)) {
            File f = new File(fileName);

            if (f.exists()) {

                return true;

            }
        } else {

        }

        return false;

    }

    /**
     * ??????????????
     *
     * @return string
     * @author: weber liu
     */
    public static String randomFilename() throws Exception {
        String str = "";
        for (int i = 0; i < 9; i++) {
            Random r = new Random();

            str += r.nextInt(9);
        }

        return System.currentTimeMillis() + str;
    }

    public static boolean makeDir(String dirName) throws Exception {

        if (null != dirName && !"".equals(dirName)) {
            File f = new File(dirName);


            if (!f.exists()) {

                f.mkdirs();
                return true;

            }
        }

        return false;

    }

    /**
     * @param src
     * @param dst
     */
    public static void copy(File src, File dst, String DIR) throws Exception {

        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(src),
                    BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst),
                    BUFFER_SIZE);

            byte[] buffer = new byte[BUFFER_SIZE];
            while (in.read(buffer) > 0) {
                out.write(buffer);
                out.flush();
            }
        } finally {
            if (null != in) {
                in.close();
            }
            if (null != out) {
                out.close();
            }
        }


        if ("0".equals(PropertiesService.getString("upload2oss"))) {
            FtpClient client = new FtpClient(
                    PropertiesService.getString("ftp.upload.ip"),
                    Integer.valueOf("21"),
                    PropertiesService.getString("ftp.upload.username"),
                    PropertiesService.getString("ftp.upload.password"));
            try {
                if (client.connect()) {

                    client.uploadFile("", PropertiesService.getString("ftp.upload.path") + "/" + DIR, dst);
                    src.delete();
                }

            } catch (Exception e) {

            } finally {
                client.disconnect();
            }
        } else {
            uploadByOss(dst, DIR);
        }
    }

    public static PutObjectResult uploadByOss(String content, String path) throws Exception {

        log.fatal("uploadByOss start....................");
        String accessKeyId = PropertiesService.getString("oss.accessKeyId").trim();
        String accessKeySecret = PropertiesService.getString("oss.accessKeySecret").trim();
        String roleArn = PropertiesService.getString("oss.roleWrite").trim();
        String roleSessionName = PropertiesService.getString("oss.roleName").trim();


        String policy = "{\n" +
                "	\"Version\": \"1\",\n" +
                "	\"Statement\": [\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "		    \"Action\": [\n" +
                "		    	\"oss:ListObjects\",\n" +
                "		    	\"oss:GetObject\"\n" +
                "		    ],\n" +
                "		    \"Resource\": [\n" +
                "		    	\"acs:oss:*:*:shouer\",\n" +
                "		   		\"acs:oss:*:*:shouer/*\"\n" +
                "		    ]\n" +
                "		},\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "			\"Action\": [\n" +
                "				\"oss:AbortMultipartUpload\",\n" +
                "				\"oss:PutObject\"\n" +
                "			],\n" +
                "			\"Resource\": [\n" +
                "				\"acs:oss:*:*:shouer\",\n" +
                "				\"acs:oss:*:*:shouer/*\"\n" +
                "			]\n" +
                "		}\n" +
                "   ]\n" +
                "}";

        ProtocolType protocolType = ProtocolType.HTTPS;
        Credentials credentials = null;

        final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
                roleArn, roleSessionName, policy, protocolType);

        if (null != response) {
            credentials = response.getCredentials();


            if (null != credentials) {

                String bucketName = PropertiesService.getString("oss.bucketName").trim();
                String endpoint = PropertiesService.getString("oss.endpoint").trim();

                String accessKeyIdByToken = credentials.getAccessKeyId();
                String accessKeySecretByToken = credentials.getAccessKeySecret();
                String securityByToken = credentials.getSecurityToken();
                OSSClient client = new OSSClient(endpoint, accessKeyIdByToken, accessKeySecretByToken, securityByToken);

                PutObjectResult result = client.putObject(bucketName, path, new ByteArrayInputStream(content.getBytes("UTF-8")));
                log.fatal(result);
                client.shutdown();

            } else {
                log.fatal("credentials is " + credentials);
            }

        } else {

            log.fatal("response is " + response);

        }


        log.fatal("uploadByOss end....................");

        return null;

    }


    public static PutObjectResult uploadByOss(File dst, String path) {

        log.fatal("uploadByOss start....................");
        String accessKeyId = PropertiesService.getString("oss.accessKeyId").trim();
        String accessKeySecret = PropertiesService.getString("oss.accessKeySecret").trim();
        String roleArn = PropertiesService.getString("oss.roleWrite").trim();
        String roleSessionName = PropertiesService.getString("oss.roleName").trim();


        String policy = "{\n" +
                "	\"Version\": \"1\",\n" +
                "	\"Statement\": [\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "		    \"Action\": [\n" +
                "		    	\"oss:ListObjects\",\n" +
                "		    	\"oss:GetObject\"\n" +
                "		    ],\n" +
                "		    \"Resource\": [\n" +
                "		    	\"acs:oss:*:*:shouer\",\n" +
                "		   		\"acs:oss:*:*:shouer/*\"\n" +
                "		    ]\n" +
                "		},\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "			\"Action\": [\n" +
                "				\"oss:AbortMultipartUpload\",\n" +
                "				\"oss:PutObject\"\n" +
                "			],\n" +
                "			\"Resource\": [\n" +
                "				\"acs:oss:*:*:shouer\",\n" +
                "				\"acs:oss:*:*:shouer/*\"\n" +
                "			]\n" +
                "		}\n" +
                "   ]\n" +
                "}";

        ProtocolType protocolType = ProtocolType.HTTPS;
        Credentials credentials = null;
        try {
            final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
                    roleArn, roleSessionName, policy, protocolType);

            if (null != response) {
                credentials = response.getCredentials();


                if (null != credentials) {

                    String bucketName = PropertiesService.getString("oss.bucketName").trim();
                    String endpoint = PropertiesService.getString("oss.endpoint").trim();

                    String accessKeyIdByToken = credentials.getAccessKeyId();
                    String accessKeySecretByToken = credentials.getAccessKeySecret();
                    String securityByToken = credentials.getSecurityToken();
                    OSSClient client = new OSSClient(endpoint, accessKeyIdByToken, accessKeySecretByToken, securityByToken);


                    InputStream content = null;
                    try {
                        content = new FileInputStream(dst);

                        ObjectMetadata meta = new ObjectMetadata();
                        meta.setContentLength(dst.length());

                        PutObjectResult result = client.putObject(bucketName, path, content, meta);
                        log.fatal(result);
                        client.shutdown();
                        return result;
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }


                } else {
                    log.fatal("credentials is " + credentials);
                }

            } else {

                log.fatal("response is " + response);

            }


        } catch (ClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }


        log.fatal("uploadByOss end....................");

        return null;

    }

    public static void uploadByOssShare(File dst, String DIR) {

        log.fatal("uploadByOss start....................");
        String accessKeyId = PropertiesService.getString("oss.accessKeyId").trim();
        String accessKeySecret = PropertiesService.getString("oss.accessKeySecret").trim();
        String roleArn = PropertiesService.getString("oss.roleWrite").trim();
        String roleSessionName = PropertiesService.getString("oss.roleName").trim();
        String endpoint = PropertiesService.getString("oss.endpoint").trim();
        String bucketName = PropertiesService.getString("oss.bucketName").trim();

        String policy = "{\n" +
                "	\"Version\": \"1\",\n" +
                "	\"Statement\": [\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "		    \"Action\": [\n" +
                "		    	\"oss:ListObjects\",\n" +
                "		    	\"oss:GetObject\"\n" +
                "		    ],\n" +
                "		    \"Resource\": [\n" +
                "		    	\"acs:oss:*:*:shouer\",\n" +
                "		   		\"acs:oss:*:*:shouer/*\"\n" +
                "		    ]\n" +
                "		},\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "			\"Action\": [\n" +
                "				\"oss:AbortMultipartUpload\",\n" +
                "				\"oss:PutObject\"\n" +
                "			],\n" +
                "			\"Resource\": [\n" +
                "				\"acs:oss:*:*:shouer\",\n" +
                "				\"acs:oss:*:*:shouer/*\"\n" +
                "			]\n" +
                "		}\n" +
                "   ]\n" +
                "}";

        ProtocolType protocolType = ProtocolType.HTTPS;
        Credentials credentials = null;
        try {
            final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
                    roleArn, roleSessionName, policy, protocolType);

            if (null != response) {
                credentials = response.getCredentials();


                if (null != credentials) {
                    String accessKeyIdByToken = credentials.getAccessKeyId();
                    String accessKeySecretByToken = credentials.getAccessKeySecret();
                    String securityByToken = credentials.getSecurityToken();
                    OSSClient client = new OSSClient(endpoint, accessKeyIdByToken, accessKeySecretByToken, securityByToken);


                    InputStream content = null;
                    try {
                        content = new FileInputStream(dst);

                        ObjectMetadata meta = new ObjectMetadata();

                        meta.setContentLength(dst.length());
                        meta.setContentDisposition("inline");
                        meta.setContentType("text/html");
                        String key = DIR + dst.getName();


                        log.fatal("key:" + key);
                        PutObjectResult result = client.putObject(bucketName, key, content, meta);
                        log.fatal(result);

                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    log.fatal("credentials is " + credentials);
                }
            } else {

                log.fatal("response is " + response);

            }
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

        log.fatal("uploadByOss end....................");

    }

    static AssumeRoleResponse assumeRole(String accessKeyId,
                                         String accessKeySecret, String roleArn, String roleSessionName,
                                         String policy, ProtocolType protocolType) throws Exception {
        IClientProfile profile = DefaultProfile.getProfile(
                PropertiesService.getString("oss.region").trim(), accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setActionName("AssumeRole");
        request.setVersion(PropertiesService.getString("oss.stsApiVersion").trim());
        request.setMethod(MethodType.POST);
        request.setProtocol(protocolType);
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy);
        AssumeRoleResponse response = client.getAcsResponse(request);
        return response;

    }


    public String uploadSinglePicProcess4VersionUpdate(File srcFile, String srcFileName, String srcFileContentTypeName) throws Exception {

        getRootPath();
        String srcFilePath = "";
        String destPath = "";
        String destFilePath = "";
        String tailSuffix = getExtension(srcFileName);
        String savePath = contextPath;

        String serverPathPrefix = null;

        if (osInfo.get("os.name").toString().contains("Windows")) {


            savePath = contextPath + File.separator + pathMap.get("windows.upload.loadPage.gallery.path");
            serverPathPrefix = (String) pathMap.get("windows.upload.loadPage.gallery.path");


        } else if (osInfo.get("os.name").toString().contains("Linux") || osInfo.get("os.name").toString().contains("linux") || osInfo.get("os.name").toString().contains("Unix") || osInfo.get("os.name").toString().contains("unix")) {


            savePath = contextPath + File.separator + pathMap.get("unix.upload.loadPage.gallery.path");

            serverPathPrefix = (String) pathMap.get("unix.upload.loadPage.gallery.path");
        }
        destPath = savePath + File.separator + DateUtils.todayDate() + File.separator;
        String uniqueName = srcFileName;
        String DIR = serverPathPrefix + "/" + DateUtils.todayDate() + "/";
        String URI = DIR + uniqueName;
        log.info("URI:" + URI);
        destFilePath = destPath + uniqueName;
        log.info("destFilePath:" + destFilePath);
        if (null != srcFile) {
            srcFilePath = srcFile.getAbsolutePath();
        } else {
            return "";
        }


        File src = new File(srcFilePath);

        File dest = new File(destFilePath);

        if (!fileExists(destPath)) {
            makeDir(destPath);

        }
        copy(src, dest, DIR);
        return URI;


    }

    public String uploadSingleFileProcess4VersionUpdate(String version, File srcFile, String srcFileName, String srcFileContentTypeName) throws Exception {

        getRootPath();
        String srcFilePath = "";
        String destPath = "";
        String destFilePath = "";
        String tailSuffix = getExtension(srcFileName);
        String savePath = contextPath;

        String serverPathPrefix = null;

        if (osInfo.get("os.name").toString().contains("Windows")) {

            savePath = contextPath + File.separator + pathMap.get("windows.upload.apk.path");
            serverPathPrefix = (String) pathMap.get("windows.upload.apk.path");

        } else if (osInfo.get("os.name").toString().contains("Linux") || osInfo.get("os.name").toString().contains("linux") || osInfo.get("os.name").toString().contains("Unix") || osInfo.get("os.name").toString().contains("unix")) {

            savePath = contextPath + File.separator + pathMap.get("unix.upload.apk.path");

            serverPathPrefix = (String) pathMap.get("unix.upload.apk.path");
        }

        destPath = savePath + File.separator + DateUtils.todayDate() + File.separator;

        String uniqueName = Constants.VERSION_PACKAGE_NAME + version;
        String defaultName = Constants.VERSION_PACKAGE_NAME;
        //???URI

        String DIR = serverPathPrefix + "/" + DateUtils.todayDate() + "/";
        String URI = DIR + uniqueName + tailSuffix;
        log.info("URI:" + URI);

        String defaultDestFilePath4Bak = savePath + File.separator + defaultName + tailSuffix + "_" + DateUtils.todayDate();

        String defaultDestFilePath = savePath + File.separator + defaultName + tailSuffix;

        destFilePath = destPath + uniqueName + tailSuffix;
        log.info("destFilePath:" + destFilePath);

        if (null != srcFile) {
            srcFilePath = srcFile.getAbsolutePath();
        } else {
            return "";
        }

        if (!fileExists(destPath)) {


            makeDir(destPath);

        }

        File src = new File(srcFilePath);

        File src4QRCode = new File(srcFilePath);

        File dest = new File(destFilePath);

        File defaultDest = new File(defaultDestFilePath);

        File defaultDest4Bak = new File(defaultDestFilePath4Bak);

        if (defaultDest.exists()) {
            copy(defaultDest, defaultDest4Bak, DIR);
        }

        if (null != defaultDest) {
            if (defaultDest.exists()) {
                defaultDest.delete();
            }

        }
        log.info("src:" + src);
        log.info("defaultDest:" + defaultDest);
        log.info("dest:" + dest);
        log.info("DIR:" + DIR);
        copy(src4QRCode, defaultDest, DIR);

        copy(src, dest, DIR);
        return URI;


    }

    public String serverPostHead(String method, Object object) {
        String timeStamp = DateUtils.getCurrentSystemDateByBreakCharacter("");
        String header = RequestUtil.genHeader(timeStamp, method);
        String postString = RequestUtil.encryptMessage(timeStamp, header, JSONObject.fromObject(object).toString());

        return HttpClientHelper.sendPostHttp(postString);

    }


}
